import {createSlice} from '@reduxjs/toolkit'
import axios from 'axios'
import { request } from '../../utils'

const foodStore = createSlice({
    name:'foods',
    initialState:{
        //商品列表
        foodsList:[],
        //菜单激活下标值
        activeIndex: 0,
        cartList:[]
    },
    reducers:{
        //修改商品列表
        setFoodList(state,action){
            state.foodsList=action.payload
        }
        ,
        //修改菜单激活下标值
        changeActiveIndex(state,action){
            state.activeIndex=action.payload
        },
        addCartList(state,action){
            const item = state.cartList.find(item=>item.id===action.payload.id)
            if(item){
                item.count++
            }else{
                state.cartList.push(action.payload)
            }
        }
    }
})

const {setFoodList,changeActiveIndex ,addCartList} = foodStore.actions
const fetchFoodList = () => {
   return async (dispatch) =>{
    const res = await request.get('/api/takeaways')
    dispatch(setFoodList(res.data.data))
   }
}
export {fetchFoodList,changeActiveIndex,addCartList}
const reducer = foodStore.reducer
export default reducer